package com.ruix.app.wxapi;

import com.ruix.app.RuiApplication;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.util.ToastUtil;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler{
	
	private static final String TAG = "MicroMsg.SDKSample.WXPayEntryActivity";
	
    private IWXAPI api;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.pay_result);
    	api = WXAPIFactory.createWXAPI(this, RuiXConstant.WX_APP_ID);
        api.handleIntent(getIntent(), this);
    }

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
        api.handleIntent(intent, this);
	}

	@Override
	public void onReq(BaseReq req) {
	}

	@Override
	public void onResp(BaseResp resp) {
		if (resp != null) {
			switch (resp.errCode) {
				case 0:
					ToastUtil.showNewMsg("订单支付成功");
					break;
				case -1:
					ToastUtil.showNewMsg("订单支付失败");
					break;
				case -2:
					ToastUtil.showNewMsg("取消订单支付");
					break;
				default:
					ToastUtil.showNewMsg("订单支付失败");
					break;
			}

			String payResultJSONString = getPayResult(resp);
			if (!TextUtils.isEmpty(payResultJSONString)) {
				//通知支付结果
				Intent intent = new Intent(RuiXConstant.NOTICE_WX_PAY_RESULT);
				intent.putExtra("WXPAY_RESULT",payResultJSONString);
				RuiApplication.getAppContext().sendBroadcast(intent);
			}
		}
		finish();
	}

	// 将支付结果转化成JSON串
	private String getPayResult(BaseResp resp) {
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("resultStatus", resp.errCode + "");
			jsonObject.put("result", resp.errStr);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		if (jsonObject != null) {
			return jsonObject.toString();
		}
		return "";
	}
}